<template>
  <div>
    <!-- 面包屑导航区 -->

    <!-- 卡片视图区 -->
    <el-card class="box-card">
      <el-row :gutter="30">
        <el-col :span="7">
          <el-input
            placeholder="请输入内容"
            v-model="input3"
            class="input-with-select"
          >
            <el-button slot="append" icon="el-icon-search"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="dialogFormVisible = true"
            >添加管理员</el-button
          >
        </el-col>
      </el-row>
      <el-table :data="tableData" border style="width: 100%; margin-top:10px">
        <el-table-column type="index" label="#"> </el-table-column>
        <el-table-column prop="username" label="用户名"> </el-table-column>
        <el-table-column prop="email" label="邮箱">
          <template slot-scope="scope">
            <span>{{
              scope.row.email == "" ? "暂未绑定邮箱" : scope.row.email
            }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="phonenumber" label="电话">
          <template slot-scope="scope">
            <span>{{
              scope.row.contactInformation == ""
                ? "暂未绑定手机号"
                : scope.row.contactInformation
            }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="type" label="角色">
          <template slot-scope="scope">
            <el-tag type="success" v-if="scope.row.roleId==1">商品管理员</el-tag>
            <el-tag type="info" v-if="scope.row.roleId==2">订单管理员</el-tag>
            <el-tag type="warning" v-if="scope.row.roleId==5">超级管理员</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch
              active-color="#13ce66"
              inactive-color="#ff4949"
              :active-value="0"
              :inactive-value="1"
              v-model="scope.row.accountStatus"
              @click.native="ban_user(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-edit"
            ></el-button>
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete"
              @click="delete_user(scope.row)"
            ></el-button>

            <el-tooltip effect="dark" content="分配角色" placement="top">
              <el-button
                size="mini"
                type="warning"
                icon="el-icon-user"
                @click="assign_role(scope.row)"
              ></el-button>
            </el-tooltip>

            <el-tooltip effect="dark" content="近期登录" placement="top">
              <el-button
                size="mini"
                type="success"
                icon="el-icon-s-platform"
                @click.native="getloing(scope.row.userId)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        width="100%"
        :current-page="index"
        :page-sizes="[5, 10, 20, 50, 100]"
        :page-size="pageSize"
        background
        pager-count="3"
        :layout="width > 1100 ? 'total, sizes, prev, pager, next, jumper' : 'total, prev, pager, next'"
        :total="totalSize"
        pageNo="1"
      >
      </el-pagination>
    </el-card>
    <!-- 近期登录 -->
    <el-dialog
      title="用户近期登录记录"
      :visible.sync="dialogVisible_1"
      :width="width<=800?'80%':'30%'"
      :before-close="handleClose"
    >
      <el-table :data="IPData" style="width: 100%">
        <el-table-column prop="loginTime" label="日期"> </el-table-column>
        <el-table-column prop="ip" label="IP"> </el-table-column>
        <el-table-column prop="userAddressDetail" label="地点">
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange_ip"
        @current-change="handleCurrentChange_ip"
        :current-page="index_ip"
        :page-sizes="[3, 10, 20, 50, 100]"
        :page-size="pageSize_ip"
        background
         :layout="width > 1100 ? 'total, sizes, prev, pager, next, jumper' : 'total, prev, pager, next'"
        :total="totalSize_ip"
        pageNo="1"
      >
      </el-pagination>
      <el-row>
        <el-col :span="24"
          ><div class="grid-content bg-purple-dark"></div
        ></el-col>
      </el-row>
      <el-button @click="dialogVisible_1 = false">取 消</el-button>
      <el-button
        style="float: right"
        type="primary"
        @click="dialogVisible_1 = false"
        >确 定</el-button
      >
    </el-dialog>
    <!-- 添加管理员 -->
    <el-dialog
    :width="width<=800?'80%':'50%'"
      title="添加管理员"
      :visible.sync="dialogFormVisible"
     
      :before-close="handleClose"
    >
      <el-form :model="user_form" :rules="rules" ref="user_form" status-icon>
        <el-form-item label="用户名" prop="username">
          <el-input v-model="user_form.username"></el-input>
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input v-model="user_form.password" show-password></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="user_form.confirmPassword " show-password></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('user_form')" :loading="add_login">
            确定
          </el-button>
          <el-button @click="dialogFormVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 角色分配 -->
   <el-dialog  :width="width<=800?'80%':'20%'" title="角色分配" :visible.sync="dialogFormVisible_2">
       <el-select v-model="role_id" placeholder="请选择">
    <el-option
      v-for="item in roleList"
      :key="item.value"
      :label="item.label"
      :value="item.value">
    </el-option>
  </el-select>
    
   
  <div slot="footer" class="dialog-footer">
    <el-button @click="dialogFormVisible_2 = false">取 消</el-button>
    <el-button type="primary" @click="fenpei">确 定</el-button>
  </div>
</el-dialog>

      
  </div>
</template>

<script>
import {
  getAdminList,
  banAdmin,
  deleteAdmin,
  checkUser,
  addAdmin,
  getUserLoginRecord,
  assignRole,
  getRoleList
} from "@/api/user_list.js";
export default {
  data() {
    var password = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        if (this.user_form.password == "") {
          callback(new Error("密码不能为空"));
        } else {
          callback();
        }
      }
    };
    var confirmPassword = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.user_form.password) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    var username = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("用户名不能为空"));
      }
       this.checkUser(this.user_form.username);
      setTimeout(() => {
       
        if (this.iftype == 0) {
          callback(new Error("用户名已被占用"));
        } else {
          callback();
        }
      }, 2000);
    };
    return {
      role_id: "",
      roleList:[],
      dialogFormVisible_2: false,
      width: 0,
      add_login: false,
      pageSize_ip: 3,
      totalSize_ip: null,
      index_ip: 1,
      dialogVisible_1: false,
      userid: "", //被点击用户id
      dialogFormVisible: false,
      iftype: 0,
      user_form: {
        username: "",
        email: "",
        phonenumber: "",
        password: "",
        confirmPassword: "",
      },
      pageSize: 10,
      totalSize: null,
      index: 1,
      tableData: [],
      rules: {
        password: [{ validator: password, trigger: "blur" }],
        confirmPassword: [{ validator: confirmPassword, trigger: "blur" }],
        username: [{ validator: username, trigger: "blur" }],
      },
    };
  },
  //获取屏幕宽度
  mounted() {
    this.width = document.body.clientWidth;
    console.log(this.width);
  },
  methods: {
    assign_role(row) {
      console.log(row);
      this.dialogFormVisible_2 = true;
      this.userid=row.userId;
    },
    //获取角色列表
    getRoleList() {
      getRoleList().then((res) => {
        //选出角色列表
        this.roleList=res.data.data.map(role => {
          console.log(role);
          return {
            label: role.name,
            value: role.id,
          };
        
        })
        console.log(this.roleList);


      });
    },

    //角色分配
    assignRole(row) {
      console.log(row);
      this.userid = row.id;
      this.dialogVisible_1 = true;

    },
    //提交角色分配
    fenpei(){
      
      let params = new URLSearchParams();
      params.append("userId", this.userid);
      params.append("roleId", this.role_id);
      assignRole(params).then((res) => {
        console.log(res);
        if (res.data.code == 200) {
          this.$message({
            type: "success",
            message: "分配成功",
          });
          this.dialogFormVisible_2 = false;
        
           this.get_userlist(this.index, this.pageSize);
        } else {
          this.$message({
            type: "error",
            message: res.data.msg,
          });
        }
      });
     assignRole(params).then(res=>{
       this.dialogFormVisible_2 = false;
       this.getAdminList();
     })
    },
    getloing(userid) {
      //获取用户最近登录信息
      this.userid = userid;
      this.dialogVisible_1 = true;
      console.log(userid);
      getUserLoginRecord({
        userId: userid,
        page: this.index_ip,
        pageSize: this.pageSize_ip,
      }).then((res) => {
        console.log(res);
        this.IPData = res.data.data.records;
        console.log(this.IPData);
        this.totalSize_ip = res.data.data.total;
      });
    },
    //提交
    submitForm(formName) {
      console.log(this.$refs[formName]);
       this.add_login = true;
      this.$refs[formName].validate((valid) => {
        if (valid) {
           
          this.add_user();
          this.dialogFormVisible = false;
          
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    //判断用户是否存在
    checkUser(val) {
      checkUser({ username: val })
        .then((res) => {
          this.iftype = 1;
        })
        .catch((err) => {
          this.iftype = 0;
          console.log(this.iftype);
        });
    },
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
      this.pageSize = val;
      this.get_userlist();
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      this.index = val;
      this.get_userlist();
    },
    get_userlist(page1, pageSize1) {
      //获取管理员列表

      getAdminList({ page: page1, pageSize: pageSize1 }).then((res) => {
        console.log(res);
        this.tableData = res.data.data.records;
        this.totalSize = res.data.data.total;
      });
    },
    ban_user(row) {
      //判断是封禁还是解封
      let mes = "";
      if (row.accountStatus == 1) {
        mes = "确定要封禁该用户吗？";
      } else {
        mes = "确定要解封该用户吗？";
      }
      this.$confirm(mes + "是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          //禁用管理员
          banAdmin({
            status: row.accountStatus,
            users: row.userId,
          }).then((res) => {
            console.log(res);
            this.get_userlist(this.index, this.pageSize);
          });
          this.$message({
            type: "success",
            message: row.accountStatus == 1 ? "封禁成功" : "解封成功",
          });
        })
        .catch(() => {
          this.get_userlist(this.index, this.pageSize);
          this.$message({
            type: "info",
            message: row.accountStatus == 1 ? "已取消封禁" : "已取消解封",
          });
        });
    },
    //添加管理员
    add_user() {
      //添加管理员
    
      addAdmin({
        username: this.user_form.username,
        password: this.user_form.password,
      }).then((res) => {
        console.log(res);
        this.add_login = false;
        this.get_userlist(this.index, this.pageSize);
        this.$message({
          type: "success",
          message: "添加成功",
        });
      });
    },
    //删除管理员
    delete_user(row) {
      //删除管理员
      this.$confirm("确定要删除该管理员吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          deleteAdmin({
            adminIds: row.userId,
          }).then((res) => {
            console.log(res);
            this.get_userlist(this.index, this.pageSize);
            this.$message({
              type: "success",
              message: "删除成功",
            });
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
  },
  created() {
    this.get_userlist(this.index, this.pageSize);
    this.getRoleList()
  },
  watch: {
    dialogFormVisible(value) {
      this.user_form.username = "";
      this.user_form.email = "";
      this.user_form.phonenumber = "";
      this.user_form.password = "";
      this.user_form.confirmPassword = "";
      console.log(this.$refs.user_form);
      this.$nextTick(() => {
        this.$refs.user_form.clearValidate();
      });
    },
  },
};
</script>

<style scoped>
.el-breadcrumb {
  margin-bottom: 15px;
  font-size: 12px;
}
.el-card {
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.15) !important;
}
.el-pagination {
  padding: 10px;
  float: right;
}
</style>
